﻿/*
*类名：QinMingWeixinUserInfo
*归属：QinMing.WeixinUserInfo命名空间
*用途：通过微信用户基础openid和基础access_token，获取微信用户的基本信息，因信息安全需要，腾讯公司已经回收了很多权限，头像、昵称等信息只能通过OAuth网页方式在经用户同意后方可获取了。
*作者：乱世刀疤
*日期：2020.05.08   2021.12.28修改
*/

using System;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using Newtonsoft.Json;  
using Newtonsoft.Json.Converters; 
using Newtonsoft.Json.Linq; 
using System.Data;
using System.Data.SqlClient;
using QinMing.Config;
using QinMing.WeixinContainer;

namespace QinMing.WeixinUserInfo
{
    public  class QinMingWeixinUserInfo : System.Web.UI.Page
    {
		
		/// <summary>
        /// 根据微信用户openid，获取其他详细信息，并更新用户表
        /// </summary>
		public void UpdateUserInfo(string openid)
		{
			SqlConnection conn = new SqlConnection(QinMingConfig.DatabaseConnStr);
			conn.Open();
			SqlCommand cmd = new SqlCommand();
			cmd.Connection = conn;
			
			string tmpUserInfo = GetUserInfo(openid);
			JObject obj = (JObject)JsonConvert.DeserializeObject(HttpUtility.UrlDecode(tmpUserInfo));
			if(obj["subscribe"].ToString().Replace("\"", "") == "1")
			{
				
				//2021年12月27日起微信方停止提供昵称和头像链接
				/*
				//执行前需判断nickname是否包含非法sql脚本字符，如'";:,>.
				string nickname = obj["nickname"].ToString().Replace("\"", "");
				if(nickname.Contains("'") || nickname.Contains("ω"))
				{
					nickname = "null";
				}
				
				cmd.CommandText = "update weixin_user_info set nickname='" + nickname + "',"
					+ "sex='" + obj["sex"].ToString().Replace("\"", "") + "',"
					+ "language='" + obj["language"].ToString().Replace("\"", "") + "',"
					+ "city='" + obj["city"].ToString().Replace("\"", "") + "',"
					+ "province='" + obj["province"].ToString().Replace("\"", "") + "',"
					+ "country='" + obj["country"].ToString().Replace("\"", "") + "',"
					+ "headimgurl='" + obj["headimgurl"].ToString().Replace("\"", "") + "',"
					//+ "unionid='" + obj["unionid"].ToString().Replace("\"", "") + "',"
					+ "remark='" + obj["remark"].ToString().Replace("\"", "") + "',"
					+ "groupid=" + obj["groupid"].ToString().Replace("\"", "") + ","
					//+ "tagid_list='" + obj["tagid_list"].ToString().Replace("\"", "") + "',"
					+ "subscribe_scene='" + obj["subscribe_scene"].ToString().Replace("\"", "") + "',"
					+ "qr_scene=" + obj["qr_scene"].ToString().Replace("\"", "") + ","
					+ "qr_scene_str='" + obj["qr_scene_str"].ToString().Replace("\"", "") + "'"
					+ "	where open_id='" + openid + "'" ;
				cmd.ExecuteScalar();
				*/
				
				cmd.CommandText = "update weixin_user_info set "
					+ "language='" + obj["language"].ToString().Replace("\"", "") + "',"
					//+ "unionid='" + obj["unionid"].ToString().Replace("\"", "") + "',"
					+ "remark='" + obj["remark"].ToString().Replace("\"", "") + "',"
					+ "groupid=" + obj["groupid"].ToString().Replace("\"", "") + ","
					//+ "tagid_list='" + obj["tagid_list"].ToString().Replace("\"", "") + "',"
					+ "subscribe_scene='" + obj["subscribe_scene"].ToString().Replace("\"", "") + "',"
					+ "qr_scene=" + obj["qr_scene"].ToString().Replace("\"", "") + ","
					+ "qr_scene_str='" + obj["qr_scene_str"].ToString().Replace("\"", "") + "'"
					+ "	where open_id='" + openid + "'" ;
				cmd.ExecuteScalar();
				
			}
			
			if (conn.State == ConnectionState.Open)
			{
				conn.Close();
				conn.Dispose();
			}
		}
		
		/// <summary>
        /// 根据微信用户openid，获取其他详细信息
        /// </summary>
		public string GetUserInfo(string openid)  
		{
			string strResult;
			string accesstoken;
			QinMingWeixinContainer gt=new QinMingWeixinContainer();
			accesstoken=gt.GetAccessToken();
			string strurl="https://api.weixin.qq.com/cgi-bin/user/info?access_token=" 
				+ accesstoken + "&openid=" + openid + "&lang=zh_CN";
			try
			{
				HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(strurl);
				HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
				Stream myStream = HttpWResp.GetResponseStream();
				StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
				StringBuilder strBuilder = new StringBuilder();
				while (-1 != sr.Peek())
				{
					strBuilder.Append(sr.ReadLine());
				}
				strResult = strBuilder.ToString();
			}
			catch
			{
				strResult = "err";
			}
			
			return strResult;
		}
	}
}